<template>
  <div class="profile-edit-container">
    <div class="profile-edit-wrapper">
      <div class="profile-edit-card">
        <!-- 头部标题 -->
        <div class="profile-header">
          <div class="header-center">
            <h2 class="title">个人信息设置</h2>
            <p class="subtitle">管理您的个人资料和账户设置</p>
          </div>
        </div>

        <!-- 用户信息展示 -->
        <div v-if="userProfile" v-loading="loading" class="user-info-section">
          <div class="avatar-section">
            <div class="avatar-container">
              <el-avatar
                :size="100"
                :src="formatAvatarUrl(userProfile.avatar)"
                :icon="UserFilled"
                class="user-avatar"
              />
              <el-button
                type="primary"
                size="small"
                class="change-avatar-btn"
                @click="showAvatarUpload = true"
              >
                更换头像
              </el-button>
            </div>
            <div class="user-basic-info">
              <h3>{{ userProfile.nickName }}</h3>
              <p class="username">@{{ userProfile.userName }}</p>
              <div v-if="userProfile.userStats" class="user-stats">
                <div class="stat-item">
                  <span class="stat-value">{{
                    userProfile.userStats.articleCount
                  }}</span>
                  <span class="stat-label">文章</span>
                </div>
                <div class="stat-item">
                  <span class="stat-value">{{
                    userProfile.userStats.followCount
                  }}</span>
                  <span class="stat-label">关注</span>
                </div>
                <div class="stat-item">
                  <span class="stat-value">{{
                    userProfile.userStats.followerCount
                  }}</span>
                  <span class="stat-label">粉丝</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 标签页 -->
        <el-tabs v-model="activeTab" class="profile-tabs">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <ProfileBasicForm
              :user-profile="userProfile"
              @success="handleUpdateSuccess"
            />
          </el-tab-pane>

          <!-- 密码修改 -->
          <el-tab-pane label="密码修改" name="password">
            <ProfilePasswordForm @success="handlePasswordChangeSuccess" />
          </el-tab-pane>

          <!-- 账户设置 -->
          <el-tab-pane label="账户设置" name="settings">
            <ProfileSettingsForm
              :user-profile="userProfile"
              @success="handleUpdateSuccess"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 头像上传对话框 -->
    <AvatarUploadDialog
      v-model:visible="showAvatarUpload"
      :current-avatar="userProfile?.avatar"
      @success="handleAvatarUploadSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { UserFilled, ArrowLeft } from "@element-plus/icons-vue";
import { useUserAuthStore } from "@/store/modules/userAuth";

import {
  getCurrentUserProfileApi,
  type UserProfile
} from "@/api/user-profile-update";
import ProfileBasicForm from "./components/ProfileBasicForm.vue";
import ProfilePasswordForm from "./components/ProfilePasswordForm.vue";
import ProfileSettingsForm from "./components/ProfileSettingsForm.vue";
import AvatarUploadDialog from "./components/AvatarUploadDialog.vue";

defineOptions({
  name: "UserProfileEdit"
});

const router = useRouter();

// 格式化头像URL
const formatAvatarUrl = (url: string): string => {
  if (!url) return "";

  // 如果已经是完整URL，直接返回
  if (url.startsWith("http://") || url.startsWith("https://")) {
    return url;
  }

  // 如果是相对路径，添加基础URL
  const baseURL = import.meta.env.DEV
    ? "http://localhost:8081"
    : "http://localhost:8081";
  return baseURL + url;
};

// 响应式数据
const userProfile = ref<UserProfile | null>(null);
const activeTab = ref("basic");
const showAvatarUpload = ref(false);
const loading = ref(false);
const searchKeyword = ref("");

// 加载用户信息
const loadUserProfile = async () => {
  try {
    loading.value = true;
    const response = await getCurrentUserProfileApi();

    if (response.code === 200) {
      userProfile.value = response.data;
    } else {
      ElMessage.error(response.message || "获取用户信息失败");
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
    ElMessage.error("获取用户信息失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 搜索、导航和返回功能已移至全局布局
// const handleSearch = (keyword: string) => {
//   console.log("搜索关键词:", keyword);
//   // 这里可以实现搜索逻辑
// };
// const goBackToProfile = () => {
//   const userAuthStore = useUserAuthStore();
//   router.push(`/user/profile/${userAuthStore.userId}`);
// };
// const handleNavClick = (nav: string) => {
//   console.log("导航点击:", nav);
//   switch (nav) {
//     case "home":
//       router.push("/user/home");
//       break;
//     case "profile":
//       router.push("/user/profile");
//       break;
//     // 可以添加更多导航处理
//   }
// };

// 处理信息更新成功
const handleUpdateSuccess = () => {
  ElMessage.success("信息更新成功");
  loadUserProfile(); // 重新加载用户信息
};

// 处理密码修改成功
const handlePasswordChangeSuccess = () => {
  ElMessage.success("密码修改成功");
  // 可能需要重新登录的提示
  ElMessage.info("为了安全起见，建议您重新登录");
};

// 处理头像上传成功
const handleAvatarUploadSuccess = (avatarUrl: string) => {
  console.log("🎉 头像上传成功，新头像URL:", avatarUrl);
  ElMessage.success("头像上传成功");
  if (userProfile.value) {
    userProfile.value.avatar = avatarUrl;
  }

  // 同时更新用户认证store中的头像
  const userAuthStore = useUserAuthStore();
  console.log("📝 更新前的userAuthStore头像:", userAuthStore.avatar);
  userAuthStore.updateAvatar(avatarUrl);
  console.log("📝 更新后的userAuthStore头像:", userAuthStore.avatar);

  showAvatarUpload.value = false;
};

// 组件挂载时加载数据
onMounted(() => {
  loadUserProfile();
});
</script>

<style scoped lang="scss">
// 响应式设计
@media (width <= 768px) {
  .profile-edit-wrapper {
    padding: 16px;
  }

  .profile-edit-card {
    border-radius: 12px;
  }

  /* 移动端返回按钮调整 */
  .back-button-container {
    top: 16px;
    left: 16px;

    .back-btn {
      padding: 8px 16px;
      font-size: 14px;
      border-radius: 6px;

      .el-icon {
        margin-right: 4px;
      }
    }
  }

  .profile-header {
    padding: 24px 20px 0;

    .header-center {
      .title {
        font-size: 24px;
      }

      .subtitle {
        margin-bottom: 20px;
        font-size: 14px;
      }
    }
  }

  .user-info-section {
    padding: 0 24px 24px;
  }

  .avatar-section {
    flex-direction: column;
    gap: 16px;
    text-align: center;

    .user-stats {
      justify-content: center;
    }
  }

  .profile-tabs {
    :deep(.el-tabs__header) {
      padding: 0 24px;
    }

    :deep(.el-tabs__content) {
      padding: 24px;
    }
  }
}

.profile-edit-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

/* 返回按钮容器 - 在内容区域左上角 */
.back-button-container {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 100;

  .back-btn {
    padding: 10px 20px;
    font-weight: 600;
    background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
    border: none;
    border-radius: 8px;
    box-shadow: 0 4px 16px rgb(64 158 255 / 30%);
    backdrop-filter: blur(10px);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 6px 20px rgb(64 158 255 / 40%);
      transform: translateY(-2px);
    }

    &:active {
      transform: translateY(0);
    }

    .el-icon {
      margin-right: 6px;
    }
  }
}

.profile-edit-wrapper {
  position: relative; /* 为绝对定位的返回按钮提供定位上下文 */
  max-width: 1000px;
  padding: 20px;
  margin: 0 auto;
}

.profile-edit-card {
  overflow: hidden;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgb(0 0 0 / 10%);
}

.profile-header {
  padding: 32px 32px 0;
  text-align: center;

  .header-center {
    .title {
      margin: 0 0 8px;
      font-size: 28px;
      font-weight: 600;
      color: #1f2937;
    }

    .subtitle {
      margin: 0 0 32px;
      font-size: 16px;
      color: #6b7280;
    }
  }
}

.user-info-section {
  padding: 0 32px 32px;
  border-bottom: 1px solid #e5e7eb;
}

.avatar-section {
  display: flex;
  gap: 24px;
  align-items: center;

  .avatar-container {
    display: flex;
    flex-direction: column;
    gap: 12px;
    align-items: center;

    .user-avatar {
      border: 3px solid #e5e7eb;
      transition: all 0.3s ease;

      &:hover {
        border-color: #409eff;
      }
    }

    .change-avatar-btn {
      padding: 4px 12px;
      font-size: 12px;
    }
  }

  .user-basic-info {
    flex: 1;

    h3 {
      margin: 0 0 4px;
      font-size: 24px;
      font-weight: 600;
      color: #1f2937;
    }

    .username {
      margin: 0 0 16px;
      font-size: 16px;
      color: #6b7280;
    }

    .user-stats {
      display: flex;
      gap: 24px;

      .stat-item {
        display: flex;
        flex-direction: column;
        align-items: center;

        .stat-value {
          font-size: 20px;
          font-weight: 600;
          color: #1f2937;
        }

        .stat-label {
          margin-top: 4px;
          font-size: 14px;
          color: #6b7280;
        }
      }
    }
  }
}

.profile-tabs {
  :deep(.el-tabs__header) {
    padding: 0 32px;
    margin: 0;
    background: #f9fafb;
  }

  :deep(.el-tabs__content) {
    padding: 32px;
  }

  :deep(.el-tabs__item) {
    font-size: 16px;
    font-weight: 500;
  }
}
</style>
